package org.lisy.java.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * Future 配合线程池使用
 * 
 * @author lisy
 */
public class FutureOperate {

    public static void main(String[] args) {
        // 创建线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        
        List<Future<Integer>> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
        	// 可以获取线程返回值及状态
        	Future<Integer> future = executorService.submit((Callable<Integer>) new AddCallableImpl(2*i, 3));
        	list.add(future);
		}
        
        while (true) {
        	if (list.size() == 0) {
        		break;
        	}
        	for (int i = list.size() - 1; i >= 0; i--) {
        		Future<Integer> future = list.get(i);
    	        if (future.isDone()) {
    		        try {
    					System.out.println("complate, result: " + future.get(3, TimeUnit.SECONDS).toString());
    					list.remove(i);
    		        } catch (Exception e) {
    					e.printStackTrace();
    					throw new RuntimeException(e);
    				}
    	        }
    		}
        	try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
        }
        
        // 关闭线程池
        executorService.shutdown();
    }

}

class AddCallableImpl implements Callable<Integer> {

    private int a;
    private int b;

    public AddCallableImpl(int a, int b) {
        this.a = a;
        this.b = b;
    }

    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName() + " start!");
		Thread.sleep(a*500);
		int c = a;
		if (a == 5) {
			c = 1/0;
		}
        System.out.println(Thread.currentThread().getName() + " end! " + (c + b));
        return c + b;
    }
}